package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.service.PayOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Aurhor: 帅的一批
 * @CreateAt: 2022/10/29 16:17
 * @Description:
 * @PACKAGE_NAME： com.cskaoyan.order.service.impl
 */
@Service
public class PayOrderServiceImpl implements PayOrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    StockMapper stockMapper;

    /**
     * 用户支付完成以后 修改状态
     * <p>
     * 1.根据订单id修改订单状态 为已支付
     * 2.查询订单中，所有的订单商品条目，针对每一个条目下单的数量，扣减lock_count
     *
     * @param orderId
     */
    @Override
    public void paySuccessAfter(String orderId) {
        try {
            Order order = new Order();
            order.setOrderId(orderId);
            //订单状态修改为已经支付
            order.setStatus(OrderConstants.ORDER_STATUS_PAYED);
            orderMapper.updateByPrimaryKeySelective(order);

            List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);

            for (OrderItem orderItem : orderItems) {
                //锁定状态就减少
                if (orderItem.getStatus() == OrderConstants.STOCK_OK) {
                    Integer num = orderItem.getNum();
                    Stock stock = new Stock();
                    stock.setItemId(orderItem.getItemId());
                    stock.setLockCount(-num);
                    stock.setStockCount((long) 0);
                    stockMapper.updateStock(stock);
                }

            }
            //修改商品条目中的status为3 库存扣减成功
            orderItemMapper.updateStockStatus(OrderConstants.STOCK_SUCCESS, orderId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(),
                    OrderRetCode.DB_EXCEPTION.getMessage());
        }
    }
}
